import { defineStore } from "pinia";
import {
  type userType,
  store,
  router,
  resetRouter,
  routerArrays,
  storageLocal
} from "../utils";
import {
  type UserResult,
  type RefreshTokenResult,
  getLogin,
  mobileLogin,
  refreshTokenApi
} from "@/api/user";
import { useMultiTagsStoreHook } from "./multiTags";
import { type DataInfo, setToken, removeToken, userKey } from "@/utils/auth";

export const useUserStore = defineStore("pure-user", {
  state: (): userType => {
    const storedData = storageLocal().getItem<DataInfo<number>>(userKey);

    return {
      // 头像
      avatar: storedData?.avatar ?? "",
      // 用户名
      username: storedData?.username ?? "",
      // 昵称
      nickname: storedData?.nickname ?? "",
      // 手机号
      contact_phone: storedData?.contact_phone ?? "",
      // 展商ID
      exhibitor_id: storedData?.exhibitor_id ?? 0,
      // 页面级别权限
      roles: storedData?.roles ?? [],
      // 按钮级别权限
      permissions: storedData?.permissions ?? [],
      // 是否勾选了登录页的免登录
      isRemembered: false,
      // 登录页的免登录存储几天，默认7天
      loginDay: 7
    };
  },
  actions: {
    /** 存储头像 */
    SET_AVATAR(avatar: string) {
      this.avatar = avatar;
    },
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username;
    },
    /** 存储昵称 */
    SET_NICKNAME(nickname: string) {
      this.nickname = nickname;
    },
    /** 存储手机号 */
    SET_CONTACT_PHONE(contact_phone: string) {
      this.contact_phone = contact_phone;
    },
    /** 存储展商ID */
    SET_EXHIBITOR_ID(exhibitor_id: number) {
      this.exhibitor_id = exhibitor_id;
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles;
    },
    /** 存储按钮级别权限 */
    SET_PERMS(permissions: Array<string>) {
      this.permissions = permissions;
    },
    /** 存储是否勾选了登录页的免登录 */
    SET_ISREMEMBERED(bool: boolean) {
      this.isRemembered = bool;
    },
    /** 设置登录页的免登录存储几天 */
    SET_LOGINDAY(value: number) {
      this.loginDay = Number(value);
    },
    /** 账号密码登录（兼容后端返回 code===1 的成功格式） */
    async loginByUsername(payload) {
      return new Promise<UserResult>((resolve, reject) => {
        getLogin(payload)
          .then((raw: any) => {
            console.log(raw);
            const isSuccess = raw?.success === true || raw?.code === 1;
            const rawData = raw?.data ?? {};

            // 规范化 token 与用户字段，兼容不同后端命名
            const normalized = {
              success: isSuccess,
              data: {
                avatar: rawData.avatar ?? "",
                username: rawData.username ?? rawData.contact_phone ?? "",
                nickname: rawData.nickname ?? "",
                contact_phone: rawData.contact_phone ?? "",
                roles: rawData.roles ?? [],
                permissions: rawData.permissions ?? [],
                accessToken:
                  rawData.accessToken ??
                  rawData.token ??
                  rawData.access_token ??
                  "",
                refreshToken:
                  rawData.refreshToken ?? rawData.refresh_token ?? "",
                // 支持多种过期字段，兜底2小时
                expires:
                  rawData.expires ??
                  rawData.expire_time ??
                  new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(),
                // 添加is_login字段
                is_login: rawData.is_login ?? 1
              },
              // 传递后端的错误信息
              msg: raw?.msg || raw?.message || "",
              code: raw?.code || 0
            } as any;

            if (normalized.success) {
              // 创建一个包含exhibitor_id的完整数据对象传递给setToken
              const tokenData = {
                ...normalized.data,
                exhibitor_id: rawData.id || 0
              };
              setToken(tokenData as any);

              // 存储用户信息到store
              this.SET_USERNAME(normalized.data.username);
              this.SET_NICKNAME(normalized.data.nickname);
              this.SET_CONTACT_PHONE(normalized.data.contact_phone);
              this.SET_EXHIBITOR_ID(rawData.id || 0);
              this.SET_ROLES(normalized.data.roles);
              this.SET_PERMS(normalized.data.permissions);
              this.SET_AVATAR(normalized.data.avatar);
            }

            resolve(normalized as any);
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    /** 短信验证码登录（兼容后端返回 code===1 的成功格式） */
    async loginByMobile(payload) {
      return new Promise<UserResult>((resolve, reject) => {
        mobileLogin(payload)
          .then((raw: any) => {
            const isSuccess = raw?.success === true || raw?.code === 1;
            const rawData = raw?.data ?? {};

            // 规范化 token 与用户字段，兼容不同后端命名
            const normalized = {
              success: isSuccess,
              data: {
                avatar: rawData.avatar ?? "",
                username: rawData.username ?? rawData.contact_phone ?? "",
                nickname: rawData.nickname ?? "",
                contact_phone: rawData.contact_phone ?? "",
                roles: rawData.roles ?? [],
                permissions: rawData.permissions ?? [],
                accessToken:
                  rawData.accessToken ??
                  rawData.token ??
                  rawData.access_token ??
                  "",
                refreshToken:
                  rawData.refreshToken ?? rawData.refresh_token ?? "",
                // 支持多种过期字段，兜底2小时
                expires:
                  rawData.expires ??
                  rawData.expire_time ??
                  new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(),
                // 添加is_login字段
                is_login: rawData.is_login ?? 1
              },
              // 传递后端的错误信息
              msg: raw?.msg || raw?.message || "",
              code: raw?.code || 0
            } as any;

            if (normalized.success) {
              // 创建一个包含exhibitor_id的完整数据对象传递给setToken
              const tokenData = {
                ...normalized.data,
                exhibitor_id: rawData.id || 0
              };
              setToken(tokenData as any);

              // 存储用户信息到store
              this.SET_EXHIBITOR_ID(rawData.id || 0);
              this.SET_USERNAME(normalized.data.username);
              this.SET_NICKNAME(normalized.data.nickname);
              this.SET_CONTACT_PHONE(normalized.data.contact_phone);
              this.SET_ROLES(normalized.data.roles);
              this.SET_PERMS(normalized.data.permissions);
              this.SET_AVATAR(normalized.data.avatar);
            }

            resolve(normalized as any);
          })
          .catch(error => reject(error));
      });
    },
    /** 前端登出（不调用接口） */
    logOut() {
      this.username = "";
      this.nickname = "";
      this.contact_phone = "";
      this.exhibitor_id = 0;
      this.roles = [];
      this.permissions = [];
      removeToken();
      useMultiTagsStoreHook().handleTags("equal", [...routerArrays]);
      resetRouter();
      router.push("/login");
    },
    /** 刷新`token` */
    async handRefreshToken(data) {
      return new Promise<RefreshTokenResult>((resolve, reject) => {
        refreshTokenApi(data)
          .then(data => {
            if (data) {
              setToken(data.data);
              resolve(data);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  }
});

export function useUserStoreHook() {
  return useUserStore(store);
}
